package com.ppp.searchHelp.core;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;

import com.aliyun.opensearch.CloudsearchSearch;
import com.ppp.searchHelp.util.StringUtil;

/**
 * 搜索帮助类
 * 
 * 
 * @author song song571377@qq.com
 * @createDate 2015/10/04
 *
 */

public class CloudsearchSearchHelp {

	
	/**
	 * 调用SDK搜索返回搜索结果
	 * 
	 * @author song
	 * 
	 * @param opts 此参数值会转为Map 其值内容参考API参数规则。{@link https://docs.aliyun.com/?spm=5176.7393634.9.7.SJLU6O#/pub/opensearch/api-reference/api-interface&search-related}
	 * @see com.aliyun.opensearch.CloudsearchSearch#search(Map)
	 * @throws ClientProtocolException
	 * @throws UnknownHostException
	 * @throws IOException
	 */
	
	public static String execSearch(JSONObject opts) throws ClientProtocolException, UnknownHostException, IOException {
		CloudsearchSearch search = PPPCore.getMe().getCloudsearchSearch();
		
		Map<String, Object> optsMap = StringUtil.jsonToMap(opts);
		
		if(!optsMap.containsKey("format") || StringUtil.isBlank(optsMap.get("format").toString())){
			optsMap.put("format", "json");
		}
		
		//indexName
		String indexNames = opts.has("indexes") ? opts.getString("indexes").trim()
				: PPPCore.getMe().getAppName();
		optsMap.put("indexes",Arrays.asList(indexNames.split(";")));
		
        
        //可以通过此参数获取本次查询需要的字段内容，多个字段使用英文分号（;）分隔
        if (opts.has("fetch_field")) {
        	optsMap.put("fetch_field",Arrays.asList(opts.getString("fetch_field").split(";")));
        }
        
        //指定要使用的查询分析规则，多个规则使用英文逗号（,）分隔
        if (opts.has("qp")) {
        	optsMap.put("qp", Arrays.asList(opts.getString("qp").split(",")));
        }
        
        if (opts.has("disable_qp")) {
        	optsMap.put("disable_qp",StringUtil.jsonToMapValArray(opts.getJSONObject("disable_qp")));
        }
        
        return search.search(optsMap);

	}

}
